import Vue from "vue";
import VueRouter from "vue-router";
import store from "../store";
import routes from "./routes";
import { loggedIn, canTurnTo } from "../util/auth";

Vue.use(VueRouter);

const home = "/home";
const title = "Laravel User Center";

const router = new VueRouter({
    linkActiveClass: "active",
    routes
});

const turnTo = (to, user, next) => {
    if (canTurnTo(to.path, user, routes)) {
        next(true);
        const { title: subTitle } = to.meta;
        document.title = `${subTitle} - ${title}`;
    }
    // 有权限，可访问
    else next({ replace: true, name: "error_401" }); // 无权限，重定向到401页面
};

router.beforeEach((to, from, next) => {
    const { state, dispatch } = store;

    if (to.path === home) return next(true);

    //validate authorized
    if (!loggedIn()) {
        return next({
            path: "/login",
            query: { redirect: to.fullPath }
        });
    }
    //if userinfo not loaded, dispatch getUserInfo action.
    const { user } = state;
    if (_.isEmpty(user)) {
        dispatch("getUserInfo").then(user => {
            turnTo(to, user, next);
        });
    } else {
        turnTo(to, user, next);
    }
});

export default router;
